public class Solution312 {
    public int maxCoins(int[] nums) {
        int n=nums.length;
        int[][] f=new int[n+2][n+2];
        for (int i=n-1;i>=0;i--){
            for (int j=i+2;j<=n+1;j++){
                for (int k=i+1;k<=j-1;k++){
                    int left=i==0?1:nums[i-1];
                    int right=j==n+1?1:nums[j-1];
                    f[i][j]=Math.max(f[i][j],f[i][k]+f[k][j]+nums[k-1]*left*right);
                }
            }
        }
        return f[0][n+1];
    }

    public static void main(String[] args) {
        System.out.println(new Solution312().maxCoins(new int[]{3,1,5,8}));
    }
}
